﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Settings;

namespace SMSROUTER.Business
{
    public partial class SmsWebService
    {
        private static object _lock = new object();
        private static List<SmsWebService> _instance;
        public static List<SmsWebService> GetInstance()
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    using (var context = new DBDataContext(AppSetting.ConnectionString))
                    {
                        _instance = context.SmsWebServices.ToList();
                    }
                }
            }
            return _instance;
        }
        public static void ReloadData()
        {
            lock (_lock)
            {
                using (var context = new DBDataContext(AppSetting.ConnectionString))
                {
                    _instance = context.SmsWebServices.ToList();
                }
            }
        }

        #region Static method
        public static SmsWebService GetByID(int id)
        {
            return GetInstance().FirstOrDefault(p => p.WebServiceID == id);
        }

        public static SmsWebService GetByCooperateIDAndRouterID(int cooperateID, int routerID)
        {
            return GetInstance().FirstOrDefault(p => p.CooperateID == cooperateID && p.RouterID == routerID);
        }

        public static List<SmsWebService> Paging(DBDataContext context, int currentPage, int pageSize, ref int totalRecord, 
            int? cooperateID, int? routerID, string urlWebService, string urlBackup)
        {
            var resutl = context.SmsWebServices.AsQueryable();
            if (cooperateID != null)
            {
                resutl = resutl.Where(p => p.CooperateID == cooperateID);
            }
            if (routerID != null)
            {
                resutl = resutl.Where(p => p.RouterID == routerID);
            }
            if (!string.IsNullOrWhiteSpace(urlWebService))
            {
                resutl = resutl.Where(p => p.URLWebService == urlWebService);
            }
            if (!string.IsNullOrWhiteSpace(urlBackup))
            {
                resutl = resutl.Where(p => p.URLBackup == urlBackup);
            }
            totalRecord = resutl.Count();
            return resutl.Skip(((currentPage - 1) < 0 ? 0 : (currentPage - 1)) * pageSize).Take(pageSize).ToList();
        }
        #endregion
    }
}
